<!--
 * @Author: Dorange.Wang
 * @Date: 2021-04-28 16:22:40
 * @LastEditors: wangming
 * @LastEditTime: 2021-08-27 14:48:07
 * @Description: file content
-->
<template>
  <el-dialog :visible="showVisible" center :show-close="false" width="600px">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ title }}</span>
        <span
          class="el-icon-close g9 f26 poi"
          @click="showVisible = false"
        ></span>
      </div>
    </div>

    <el-form
      class="pl30 pr30"
      :model="formData"
      ref="form"
      label-width="120px"
      label-position="right"
    >
      <el-form-item
        :label="title"
        prop="componentIds"
        :rules="[
          { required: true, message: `${$t('sys.please_select')}${title}`, trigger: 'change' },
        ]"
      >
        <el-select
          value-key="id"
          v-model="formData.componentIds"
          multiple
          filterable
          style="width: 400px"
        >
          <el-option
            v-for="item in components"
            :key="item.id"
            :value="item"
            :label="item.title"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <div slot="footer" class="tr">
      <el-button @click="showVisible = false">{{$t('sys.cancel')}}</el-button>
      <el-button type="primary" :loading="loading" @click="submit">{{$t('sys.confirm')}}</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      default: ''
    },
    components: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      loading: false,
      showVisible: false,
      formData: {},
      callback: null
    }
  },

  watch: {
    showVisible(value) {
      if (value) {
        this.loading = false;
      }
    },
  },

  methods: {
    open (data = {}, callback = null) {
      this.$set(this.formData, 'componentIds', undefined)
      this.showVisible = true
      this.callback = callback
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },

    async submit () {
      this.loading = true
      try {
        await this.$refs.form.validate()
        const { componentIds } = this.formData
        this.callback &&
          this.callback(
            componentIds.map(({ id, businessType }) => ({ id, businessType }))
          )
        this.showVisible = false
      } catch (error) {
       this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
